<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
    <div>
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2>进行中订单</h2>
            <button type="button" class="btn btn-primary" onclick="refreshOrders()">
                <i class='bx bx-refresh'></i> 刷新
            </button>
        </div>

        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>订单编号</th>
                        <th>预约时间</th>
                        <th>回收地址</th>
                        <th>联系人</th>
                        <th>联系电话</th>
                        <th>回收物品</th>
                        <th>预估重量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:if="${#lists.isEmpty(orders)}">
                        <td colspan="8" class="text-center">暂无进行中订单</td>
                    </tr>
                    <tr th:each="order : ${orders}">
                        <td th:text="${order.orderNo}">-</td>
                        <td th:text="${#temporals.format(order.appointmentTime, 'yyyy-MM-dd HH:mm')}">-</td>
                        <td th:text="${order.address}">-</td>
                        <td th:text="${userMap[order.userId]?.realName}">-</td>
                        <td th:text="${order.contactPhone}">-</td>
                        <td>
                            <span class="badge bg-info" th:each="item : ${order.itemType}" 
                                  th:text="${item == 'PLASTIC' ? '塑料' : 
                                           item == 'METAL' ? '金属' : 
                                           item == 'PAPER' ? '纸类' :
                                           item == 'GLASS' ? '玻璃' :
                                           item == 'FABRIC' ? '布料' :
                                           item == 'ELECTRONICS' ? '电子产品' : item}">物品</span>
                        </td>
                        <td th:text="${order.estimatedWeight != null ? #numbers.formatDecimal(order.estimatedWeight, 1, 1) + ' kg' : '-'}">-</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-success" 
                                    th:attr="data-order-id=${order.id}"
                                    onclick="completeOrderByData(this)">
                                <i class="bx bx-check-double"></i> 完成
                            </button>
                            <button type="button" class="btn btn-sm btn-info" 
                                    th:attr="data-lat=${order.latitude},
                                            data-lng=${order.longitude},
                                            data-address=${order.address}"
                                    onclick="navigateToOrderByData(this)">
                                <i class="bx bx-navigation"></i> 导航
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script th:fragment="script" th:inline="javascript">
        // 页面加载完成后执行
        $(document).ready(function() {
            console.log('进行中订单页面加载完成');
            
            // 检查按钮是否存在
            console.log('完成按钮数量:', $('.complete-order-btn').length);
            console.log('导航按钮数量:', $('.navigate-btn').length);

            // 使用事件委托绑定按钮事件
            $(document).on('click', '.complete-order-btn', function(e) {
                e.preventDefault();
                const orderId = $(this).data('order-id');
                console.log('完成按钮被点击，订单ID:', orderId);
                completeOrder(orderId);
            });

            $(document).on('click', '.navigate-btn', function(e) {
                e.preventDefault();
                const lat = $(this).data('lat');
                const lng = $(this).data('lng');
                const address = $(this).data('address');
                console.log('导航按钮被点击，参数:', {lat, lng, address});
                navigateToOrder(lat, lng, address);
            });
        });

        // 刷新订单列表
        function refreshOrders() {
            console.log('刷新订单列表');
            
            // 显示加载中提示
            Swal.fire({
                title: '刷新中...',
                text: '正在获取最新订单',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // 发送AJAX请求获取最新订单列表
            $.get('/collector/orders/processing/list', function(response) {
                // 更新订单列表内容
                $('#orderList').html(response);
                
                // 关闭加载提示
                Swal.close();
                
                // 显示刷新成功提示
                const toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000
                });
                toast.fire({
                    icon: 'success',
                    title: '订单列表已更新'
                });
            }).fail(function(xhr, status, error) {
                console.error('刷新订单列表失败:', {status, error, response: xhr.responseText});
                Swal.fire({
                    title: '刷新失败',
                    text: '获取订单列表失败，请重试',
                    icon: 'error'
                });
            });
        }
        
        // 完成订单处理
        function completeOrder(orderId) {
            if (!orderId) {
                Swal.fire({
                    title: '错误',
                    text: '订单ID不能为空',
                    icon: 'error'
                });
                return;
            }
            
            Swal.fire({
                title: '确认完成订单',
                text: "确认已完成该订单的回收工作？",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '确认完成',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: '处理中...',
                        text: '正在提交完成请求',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    $.ajax({
                        url: '/api/orders/' + orderId + '/complete',
                        type: 'POST',
                        success: function(response) {
                            Swal.fire({
                                title: '订单已完成！',
                                text: '订单已添加到您的已完成订单列表',
                                icon: 'success'
                            }).then(() => {
                                window.location.reload();
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('完成订单请求失败:', {status, error, response: xhr.responseText});
                            Swal.fire({
                                title: '操作失败',
                                text: xhr.responseText || '请稍后重试',
                                icon: 'error'
                            });
                        }
                    });
                }
            });
        }
        
        // 导航到订单地点
        function navigateToOrder(lat, lng, address) {
            if (!lat || !lng) {
                Swal.fire({
                    title: '无法导航',
                    text: '订单地址信息不完整',
                    icon: 'error'
                });
                return;
            }
            
            Swal.fire({
                title: '确认导航',
                text: `是否导航到地址: ${address}`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '开始导航',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `/collector/map?lat=${lat}&lng=${lng}`;
                }
            });
        }
    </script>
</body>
</html> 